package com.swxc.smartorder.ui.activity

import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.TextView
import com.google.gson.reflect.TypeToken
import com.jakewharton.rxbinding2.widget.RxTextView
import com.lzy.okgo.model.HttpParams
import com.swxc.smartorder.R
import com.swxc.smartorder.adapter.AdapterContact
import com.swxc.smartorder.app.GlobalAPI
import com.swxc.smartorder.entity.*
import com.swxc.smartorder.network.NetworkHelper
import com.swxc.smartorder.pinyin.CharacterParser
import com.swxc.smartorder.pinyin.PinyinComparator
import com.swxc.smartorder.ui.base.BaseActivity
import com.swxc.smartorder.utils.JsonUtil
import com.swxc.smartorder.utils.ToastUtil
import com.swxc.smartorder.widget.QuickIndexBar
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_contact_list.*
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager
import java.util.*
import java.util.concurrent.TimeUnit


/**
 * 联系人
 */
class ContactListActivity : BaseActivity(), View.OnClickListener {


    private val pinyinComparator = PinyinComparator()
    private var statusLayoutManager: StatusLayoutManager? = null
    private var mHelper: NetworkHelper? = null
    var mList: MutableList<ContactSection>? = null
    var nameList: MutableList<String>? = null
    var contactList: MutableList<ContactEntity>? = null
    var mAdapter: AdapterContact? = null
    private var mOrderId: Long? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_contact_list)

        mHelper = NetworkHelper(mContext, supportFragmentManager)
        initBundleData()
        initViewAndEvent()
        initData()
        initEmptyView()
    }

    override fun onClick(v: View?) {

        when (v?.id) {
            R.id.tv_cancel -> {
                finish()
            }

        }
    }

    private fun initEmptyView() {
        val emptyView = layoutInflater.inflate(R.layout.layout_contact_empty, null, false)

        val tvEmpty = emptyView.findViewById<TextView>(R.id.tv_empty)

        tvEmpty.text = "哎呀\n没有找到相关信息"
        statusLayoutManager = StatusLayoutManager.Builder(rv_contact)
                .setEmptyLayout(emptyView)
                .setErrorLayout(R.layout.layout_error)
                .setDefaultLayoutsBackgroundColor(Color.WHITE)
                .setOnStatusChildClickListener(object : OnStatusChildClickListener {
                    override fun onErrorChildClick(p0: View?) {
                        initData()
                    }

                    override fun onEmptyChildClick(p0: View?) {
                    }

                    override fun onCustomerChildClick(p0: View?) {
                    }
                })
                .build()
    }

    private fun initBundleData() {
        mOrderId = intent.extras.getLong("mOrderId")


    }

    private fun initData() {

        val httpParams = HttpParams()
        httpParams.put("fields", "staffName,staffId,orgName,staffPhone,avatar")
        httpParams.put("search", "")
        httpParams.put("page.no", 1)
        httpParams.put("page.size", 50)
        mHelper?.getRequest(GlobalAPI.contactList!!, httpParams, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {


                val type = object : TypeToken<CommonData<CommonListData<ContactEntity>>>() {}.type
                val fromJson = JsonUtil.fromJson<CommonData<CommonListData<ContactEntity>>>(json, type)
                        ?: return
                when (fromJson.responseCode) {
                    1001 -> {
                        fromJson.data.elements.forEach {
                            contactList?.add(it)
                            val pair = getFirstString(it)
                            if (!nameList?.contains(pair)!!) {
                                nameList?.add(pair)
                            }
                        }

                        Collections.sort(nameList, pinyinComparator)
                        quick_index_bar.indexList = nameList
                        nameList?.forEach {
                            val type = it
                            val header = ContactSection(true, it)
                            mList?.add(header)
                            contactList?.forEach {
                                val flag = getFirstString(it)
                                if (flag == type) {
                                    val entity = ContactSection(it)
                                    mList?.add(entity)
                                }
                            }
                        }

                        mAdapter?.notifyDataSetChanged()
                    }
                }
            }

            override fun requestFail() {
            }
        })
    }


    /**
     * 获取姓名首拼的大写字母
     */
    private fun getFirstString(it: ContactEntity): String {
        var sortName: String? = null
        val pinyin = CharacterParser.getInstance().getSelling(it.staffName)
        val sortString = pinyin.substring(0, 1).toUpperCase()
        sortName = if (sortString.matches("[A-Z]".toRegex())) {
            sortString
        } else {
            "#"
        }
        return sortName
    }

    private fun initViewAndEvent() {
        tv_cancel.setOnClickListener(this)
        mList = ArrayList()
        nameList = ArrayList()
        contactList = ArrayList()
        mAdapter = AdapterContact(mList)
        rv_contact.layoutManager = LinearLayoutManager(this)
        rv_contact.adapter = mAdapter

        quick_index_bar.setOnIndexChangeListener(object : QuickIndexBar.OnIndexChangeListener {
            override fun onIndexChange(selectIndex: Int) {
                val letter = quick_index_bar.indexList[selectIndex]
                tv_center.text = letter
                tv_center.visibility = View.VISIBLE
                val letterPosition = mAdapter?.getLetterPosition(letter)

                if (letterPosition != -1) {

                    letterPosition?.let { rv_contact.scrollToPosition(it) }
                    val mLayoutManager = rv_contact.layoutManager as LinearLayoutManager
                    letterPosition?.let { mLayoutManager.scrollToPositionWithOffset(it, 0) }
                }


            }

            override fun onActionUp() {
                tv_center.visibility = View.GONE
            }
        })

        tv_submit.setOnClickListener {
            val checkedPosition = mAdapter?.checkedPosition
            if (checkedPosition == -1) {
                val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_COMMON, "你好像还没有选择需要转交的员工")
                toastUtil.show(2000)
            } else {
                val contactEntity = mAdapter?.data!![checkedPosition!!]
                val item = contactEntity.contactEntity

                mHelper?.handOrder("", "", mOrderId, item?.staffId, "TRANSFER", object : NetworkHelper.NetWorkHelperBack {
                    override fun requestSuccess(json: String) {

                        val fromJson = JsonUtil.fromJson<BackEntity>(json, BackEntity::class.java)
                                ?: return
                        when (fromJson.responseCode) {
                            1001 -> {
                                val toastUtil = ToastUtil(mContext, true, ToastUtil.STATUS_SUCCESS, "转交成功")
                                toastUtil.show(2500)
                                finish()
                            }
                            else -> {
                                val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_ERROR, "转交失败")
                                toastUtil.show(2500)
                            }
                        }
                    }

                    override fun requestFail() {
                    }
                })
            }

        }

        RxTextView.textChangeEvents(edt_search)
                .debounce(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())  //触发后回到Android主线程调度器
                .subscribe({
                    val key = it.text().toString().trim()
                    if (!key.isEmpty()) {
                        val filter = mList?.filter {
                            !it.isHeader && (it.contactEntity.staffPhone.contains(key) || it.contactEntity.staffName.contains(key))
                        }

                        if (filter?.size == 0) {
                            statusLayoutManager?.showEmptyLayout()
                        } else {
                            statusLayoutManager?.showSuccessLayout()
                            mAdapter?.setNewData(filter)
                            mAdapter?.notifyDataSetChanged()
                        }
                    } else {
                        mAdapter?.setNewData(mList)
                        mAdapter?.notifyDataSetChanged()
                    }

                })


    }
}
